package com.example.musicplayer;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.example.musicplayer.listener.MusicHandlerListener;
import com.example.musicplayer.model.BroadActions;
import com.example.musicplayer.model.Music;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MusicService extends Service {
    final List<IMusicServiceCallback> callbacks = new CopyOnWriteArrayList<>();
    MediaPlayer player;// 播放器
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    final String TAG = "MusicService";

    static MusicHandlerListener listener;

    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    public MusicService() {

    }

    public static void setListener(MusicHandlerListener l) {
        listener = l;
    }

    IBinder iMusicService = new IMusicService.Stub() {
        @Override
        public void pausePlay() {
            player.pause();
            Intent intent = new Intent();
            intent.setAction(BroadActions.PAUSE_MUSIC);
            sendBroadcast(intent);
            Log.d(TAG, "pausePlay: ====>" + "暂停音乐");
        }

        @Override
        public void ContinuePlay() throws RemoteException {
            player.start();
            Intent intent = new Intent();
            intent.setAction(BroadActions.CONTINUE_MUSIC);
            sendBroadcast(intent);
            Log.d(TAG, "ContinuePlay: ====>" + "继续播放音乐");
        }

        @Override
        public void seekTo(int progress) throws RemoteException {
            player.seekTo(progress);
            Log.d(TAG, "seekTo: ====>" + "音乐进度条" + progress);
        }

        @Override
        public void Play(int i) throws RemoteException {
            try {
                Uri uri = Uri.parse("android.resource://" + getPackageName() + "/raw/" + "music_0" + (i + 1));
                // 播放器重新开始播放
                player.reset();
                player = MediaPlayer.create(getApplicationContext(), uri);
                player.start();
                addTimer();
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "Play: 出错了");
            }
            Log.d(TAG, "Play: =====>" + "切换/开始播放音乐第" + (i + 1) + "首");
        }

        @Override
        public void RegisterCallback(IMusicServiceCallback callback) {
            if (callback != null) {
                callbacks.add(callback);
            }
        }

        @Override
        public void unRegisterCallback(IMusicServiceCallback callback) {
            if (callback != null) {
                callbacks.remove(callback);
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: 服务已启动！");
        return iMusicService;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: 服务已结束！");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player == null) {
            return;
        }
        if (player.isPlaying()) {
            player.stop();
        }//停止播放音乐
        player.release();//释放占用的资源
        player = null;//将player置为空
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
    }

    /**
     * 添加一个计时器刷新ui那边的进度条的
     */
    void addTimer() {
        // Runnable
        Runnable task = () -> {
            if (player == null) return;
            // 获取歌曲进度基本信息
            int duration = player.getDuration();
            int curPos = player.getCurrentPosition();

            Bundle bundle = new Bundle();
            Log.d(TAG, "addTimer:===>时长:" + duration + "目前进度:" + curPos);
//            bundle.putInt("duration", duration);
//            bundle.putInt("curPos", curPos);

//            // 把bundle给msg
//            listener.sendMsgToHandler(1, bundle);
            for (IMusicServiceCallback callback : callbacks) {
                try {
                    callback.updateProgress(duration, curPos);
                } catch (RemoteException e) {
                    Log.d(TAG, "addTimer: 出错了");
                }
            }
        };
        scheduledExecutorService.scheduleWithFixedDelay(task, 5, 500, TimeUnit.MILLISECONDS);
    }
}